package com.macro.mall.runner;

import com.macro.mall.common.api.EsIndexDto;
import com.macro.mall.remote.EsProductRemote;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Author：Minxiao-Hao
 * @Description:
 * @name：EsIndexMappingRunner
 * @Date：2024/10/17 15:17
 */
@Component
@Slf4j
public class EsIndexMappingRunner implements ApplicationRunner {

    @Autowired
    private EsProductRemote esDocRemote;

    private static final String INDEX_NAME = "product";
    private static final String JSON_FILE_PATH = "product.json";

    @Override
    public void run(ApplicationArguments args) {
        if (isIndexExists()) {
          log.info("索引已经存在,无序创建");
        }

        log.info("开始创建 ES 索引 '{}'", INDEX_NAME);
        createIndex();
    }

    private boolean isIndexExists() {
        Boolean exists = (Boolean) esDocRemote.exists(INDEX_NAME).getData();
        return Boolean.TRUE.equals(exists);
    }

    private void createIndex() {
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(JSON_FILE_PATH)) {
            if (inputStream == null) {
                log.error("未找到 JSON 文件 '{}'", JSON_FILE_PATH);
                return;
            }

            String jsonContent = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
            log.info("读取到 JSON 内容: {}", jsonContent);

            EsIndexDto esIndexDto = new EsIndexDto();
            esIndexDto.setIndexName(INDEX_NAME);
            esIndexDto.setIndexMappings(jsonContent);

            esDocRemote.createIndex(esIndexDto);
            log.info("初始化成功，索引 '{}' 创建完毕", INDEX_NAME);
        } catch (Exception e) {
            log.error("读取或处理 JSON 文件时发生错误", e);
        }
    }
}
